﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MarsRover
{
    class Surface : ISurface
    {
        private readonly IList<IRover> _rovers;

        private Surface()
        {
        }

        public Surface(int width, int height)
        {
            if (width <= 0 || height <= 0)
            {
                throw new ArgumentOutOfRangeException("width and height must be greater than zero");
            }

            Width = width;
            Height = height;

            _rovers = new List<IRover>();
        }

        public int Width { get; private set; }
        public int Height { get; private set; }

        public int AddRover(int x, int y, Heading heading)
        {
            if (!IsRoverPositionCorrect(x, y))
            {
                throw new ArgumentOutOfRangeException("Rover's position is incorrect");
            }

            IRover rover = new Rover(x, y, heading);
            _rovers.Add(rover);
            return _rovers.IndexOf(rover);
        }

        public IRover GetRover(int roverId)
        {
            return _rovers.ElementAtOrDefault(roverId);
        }

        private bool IsRoverPositionCorrect(int x, int y)
        {
            return (x >= 0) && (x < Width) &&
                (y >= 0) && (y < Height);
        }

        public bool IsRoverAbleToMove(IRover rover)
        {
            var newPosition = rover.GetNextPosition();
            return IsRoverPositionCorrect(newPosition.X, newPosition.Y);
        }
    }
}
